package com.augurit.wf.app.document.web;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import org.apache.struts2.convention.annotation.ExceptionMapping;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;

import com.augurit.common.base.action.CrudActionSupport;
import com.augurit.common.base.action.ExtBaseAction;
import com.augurit.common.system.util.WebContextUtils;
import com.augurit.common.util.lang.StringUtils;
import com.augurit.wf.app.document.service.IdocCategory;

@Results({
	@Result(name = CrudActionSupport.SUCCESS,type="stream",params={"contentType", "text/plain","inputName","inputStream",
			"contentDisposition","attachment;fileName=${downloadFileName}","bufferSize","4096"
	})
	
})
//用户取消下载时
@ExceptionMapping(exception="org.apache.catalina.connector.ClientAbortException",result="/astat/document/document-manager.jsp")

public class DownloadAction  extends ExtBaseAction {
	
	private String fileName;//初始的文件名
	
	private String id;
	
	@Autowired
	private IdocCategory docCategoryImpl;
	
	
	private InputStream inputStream;
	
	
	
	

	//经过转码后的文件名（解决中文问题）
	public String getDownloadFileName() {
		String downFileName =null;
		if("-1".equals(id)){
			downFileName =StringUtils.substring(WebContextUtils.HELP_DOC_PATH, 4);
		}else{
			downFileName = docCategoryImpl.findDocFileName(Long.valueOf(id));
		}
		
		try {

		downFileName = new String(downFileName.getBytes(), "ISO8859-1");

		} catch (UnsupportedEncodingException e) {

		e.printStackTrace();

		}

		return downFileName;

		}

		
	
	public void setFileName(String name){
		this.fileName=name;
	}



	public Object getInputStream()throws Exception{
		InputStream inputStream =null;
		
		try {
			String url =null;
			if(id!=null&&id.length()>0){
				if("-1".equals(id)){
					url=WebContextUtils.HELP_DOC_PATH;
				}else{
					url=docCategoryImpl.findDocUrl(Long.valueOf(id));
				}
			}
			File newFile =null;
			if(url!=null && url.length()>0)
			{   
				String myurl=this.getSysRealPath()+url.substring(7);
			    newFile =new File(myurl);
			}
			if(newFile.exists())
				inputStream= new FileInputStream(newFile);
			
		} catch (RuntimeException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
			if(inputStream!=null){
				return  inputStream;}
			else {
				//怎样用窗口提示用户文件不存在
				//this.renderHtml("文件不存在");
				return null;
				
			}
		
		
	}
	
	
	
	



	public String getId() {
		return id;
	}



	public void setId(String id) {
		this.id = id;
	}



	

}
